﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using FlashCards.Model;

namespace FlashCards.WebApp.DataAccessLayer
{
    public class UserUtils
    {
        public static int CreateUser(User user, Membership membership)
        {
            using (var context = new FlashCardsEntities())
            {
                User newUser = new User();
                newUser.Nick = user.Nick;
                newUser.Name = "temp";
                newUser.AvatarId = 1;

                context.Users.AddObject(newUser);
                context.SaveChanges();

                Membership newMembership = new Membership();
                newMembership.Password = membership.Password;
                newMembership.User = newUser;
                newMembership.Email = membership.Email;
                newMembership.FailedLoginAttemptCount = 0;
                newMembership.IsLocked = false;
                newMembership.LastFailedLoginAttemptDate = DateTime.MinValue;

                context.Memberships.AddObject(newMembership);
                context.SaveChanges();

                return newUser.UserId;
            }
        }

        public static User GetUser(string nick)
        {
            using (var context = new FlashCardsEntities())
            {
                return context.Users.Where(x => x.Nick == nick).FirstOrDefault();
            }
        }

        public static User GetUser(int userId)
        {
            using (var context = new FlashCardsEntities())
            {
                return context.Users.Where(x => x.UserId == userId).FirstOrDefault();
            }
        }

        /// <summary>
        /// Zwraca id uzytkownika o danym nicku
        /// </summary>
        /// <param name="nick"></param>
        /// <returns></returns>
        public static int? GetUserId(string nick)
        {
            using (var context = new FlashCardsEntities())
            {
                var user = context.Users.FirstOrDefault(x => x.Nick == nick);
                if(user != null)
                    return user.UserId;

                return null;
            }
        }

        public static byte [] GetUserAvatarData(int userId)
        {
            using (var context = new FlashCardsEntities())
            {
                var avatar = context.Users.Where(x => x.UserId == userId).Select(x => x.Avatar).FirstOrDefault();
                return avatar.Data;
            }
        }

        public static List<User> GetUsersOrderByLastLoginDate()
        {
            using (var context = new FlashCardsEntities())
            {
                var users = context.Users.Include("Membership")
                    .OrderByDescending(x => x.Membership.LastLoginDate)
                    .ToList();

                return users;
            }
        }
    }
}